/**
 * Created by Sherry on 2016/12/23.
 */
import Vue from 'vue';
import Util from '../libs/util';
// import Config from '../config/config'
import Request from '../config/request'
class User{
    constructor(isLogin=false,userInfo=null,token='',timeout=0,uid='',openid='',couponNum=0,isFocus=0,payRecord={},isWeixin="micromessenger" == window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i),otherUser={}){
        this.isLogin=isLogin;
        this.userInfo=userInfo;
        this.token=token;
        this.timeout=timeout;
        this.uid=uid;
        this.openid=openid;
        this.couponNum=couponNum;
        this.isFocus=isFocus;
        this.payRecord=payRecord;
        this.isWeixin=isWeixin;
        this.otherUser=otherUser

    }
    init(query){
        let self = this,
            queryData = query,
            userInfo = localStorage.getItem('USER');
            console.log(queryData);
        if (queryData.res == 'clear') {

            localStorage.removeItem('CART');

            history.replaceState(history.state, null, this.getNoCodeHref(queryData));
        }

        if (!!queryData.token) {
            console.log('存在token')
            this.token = queryData.token;
            this.openid=queryData.openid;
            this.timeout = Date.now() + 86400000;
            this.isFocus=queryData.isFocus;
            this.isLogin=true;
            history.replaceState(history.state, null, this.getNoCodeHref(queryData));
            return  this.getUser();;
        } else {
           return  this.checkUser();
        }
    }
    getNoCodeHref(query) {
        console.log(query)
        let search = query,
            href = window.location.origin + window.location.pathname;
        delete search.code;
        delete search.state;
        delete search.from;
        delete search.isappinstalled;
        delete search.token;
        delete search.res;
        delete search.openid;
        search = Util.objToQueryString(search);
        return href + (search == '' ? '' : '?' + search);
    }
    checkUser() {
        let user = localStorage.getItem('USER');

        console.log(this.couponNum)
        if (!!user) {
            user = JSON.parse(user);
        }



        if (user && user.token && user.timeout > Date.now()) {
            if (user.id) {
                this.saveUser(user.token, user.timeout, user.id,user.isFocus,user.couponNum);
                return true;
            } else {
                this.token = user.token;
                this.timeout = user.timeout;
                return  this.getUser();
            }
        } else {
            this.removeUser();
            return false;
        }
    }
    saveUser(token, timeout=(Date.now() + 86400000), id,isFocus,couponNum) {
        if (!token) {
            return;
        }

        let obj = {
            token: token,
            timeout: timeout ,
            id: id,
            isFocus:isFocus,
            couponNum:couponNum
        };
        localStorage.setItem('USER', JSON.stringify(obj));
        this.token = obj.token;
        this.uid = obj.id;
        this.timeout = obj.timeout;
        this.isLogin = true;
        this.isFocus=obj.isFocus;
        this.couponNum=obj.couponNum;
        console.log(this.couponNum)
        return obj;
    }
    removeUser() {
        this.isLogin = false;
        this.userInfo = null;
        this.token = '';
        this.timeout = 0;
        this.uid = '';
        localStorage.removeItem('USER');
    }
    async login(phone, password) {
        let resolve=await Request.post(Config.apiDomain+'/User/Login',{data:{phone: phone,password: password}});
        if (resolve.status == 200 && resolve.data.token) {
            console.log(resolve)
            this.token = resolve.data.token;
            this.timeout = Date.now() + 86400000;
            return await this.getUser();
        }
        else {
            resolve.loginFail = true
            return resolve;
        }
    }


    //返回user对象
    async getUser() {
        console.log('getUser')
        let res=await Request.post(Config.apiDomain + '/Member/getUserCenter?token='+this.token)
        if (res.status == 200 && !!res.data && !!res.data.item && res.data.item.length > 0) {
            this.uid = res.data.item[0].id;
            this.couponNum=Number.parseInt(res.data.item[0].coupon_num);
            this.isFocus=res.data.item[0].isFocus
            console.log(this.couponNum)
            console.log(res.data)
            this.saveUser(this.token, this.timeout, this.uid,this.isFocus,this.couponNum);
            return res;
        }
        return false;
    }
    async getMessage(){
        let res=await Request.post(Config.apiDomain + '/Member/getUserMessage?token='+this.token)
        if(res.status == 200 && !!res.data && !!res.data.item && res.data.item.length > 0){
            this.uid=res.data.item[0].id;
        }
        return res;
    }


    async setUserName(name=''){
        let res=await Request.post(Config.apiDomain + '/Member/setUserName?token='+this.token,{data:{username:name}})
        return res;
    }

    async verifyPhone(code='',password=''){
        let res=await Request.post(Config.apiDomain + '/Common/verifyPhone?token='+this.token,{data:{code:code,password:password}})
        return res;
    }

    async sendSMS(phone=''){
        let res=await Request.post(Config.apiDomain + '/Common/sendSMS?token='+this.token,{data:{phone:phone}})
        return res;
    }
    
    
    
    async getRecordByFunction(page=1,type='getMyAlreadyAnnounced'){
        let res=await Request.post(Config.apiDomain + '/Member/'+type+'?token='+this.token,{data:{
            page:page
        }})

        return res;
    }

    async getWinRecord(page=1){
        let res=await Request.post(Config.apiDomain + '/Member/getMyWinRecord?token='+this.token,{data:{
            page:page
        }})
        return res;
    }
    
    async getOtherWinRecord(id = 0,page = 0){

        let res=await Request.post(Config.apiDomain + '/Member/getUserWinRecord',{data:{
            
            id:id,
            limit: 10,
            offset: page * 10

        }})
        return res;
        
    }

    async getMyGroupList(page=0,type=0){
        let res=await Request.post(Config.apiDomain + '/grouporder/showMyOrder',{data:{
            page: page,
            type: type,
            token:this.token
        }})

        return res;
    }

    async getMoney(){
        let res = await Request.post(Config.apiDomain + '/Member/getUserMoney?token='+this.token)
        
        return res;
    }

    async getOrder(type,cart,coupon){
        let res = Request.post(Config.apiDomain + '/Order/createOrder?token=' + this.token,{data: {
            type: type,
            data: JSON.stringify(cart),
            coupon_ids: coupon
        }})

        return res;

    }

    async getUserPayOrder(page){
        let res = await Request.post(Config.apiDomain + '/Member/getUserPayRecord?token=' + this.token,{data:{limit: 10,
            offset: (page || 0) * 10
        }});

        return res;
    }

    async checkoutPay(buyType,goodsid){
        let res = await Request.post(Config.apiDomain + '/pingtuan/checkout',{data:{
            productid : Number.parseInt(goodsid),
            buyType  : Number.parseInt(buyType),
            token:this.token
        }})

        return res;
    }

    async createOrder(tuanid,id,buyType,g_number){
        let res = await Request.post(Config.apiDomain + '/grouporder/createOrder',{data:{
            g_id : tuanid,
            s_id   : Number.parseInt(id),
            token:this.token,
            group_type:buyType,
            g_num:Number.parseInt(g_number)
        }})
        
        return res;
    }
    
    async groupDetail(g_id){
        let res = await Request.post(Config.apiDomain + '/pingtuan/detail',{data: {
            tuanid : g_id,
            token:this.token
        }})

        return res;
        
    }

    async getOtherMessage(id) {

        if (this.otherUser[id]) {

            return this.otherUser[id];

        }

        let res = await Request.get(Config.apiDomain + '/Member/getOtherMessage?id='+Number.parseInt(id));

        this.otherUser[id] = res;

        return res;

    }

    async getBuyRecord(id = 0,page = 0){

        let res = await Request.post(Config.apiDomain + '/Member/getOtherBuyRecord',{data:{id:id,limit:10,offset:page * 10}});

        return res;

    }
    
    async getShareList(id = 0,page = 0){
        
        let res = await Request.post(Config.apiDomain + '/Shareorder/getUserShareByUID',{data:{id:id,limit:10,offset:page * 10}});
        return res;
    }


    async getWinDetail(id){

        let res = await Request.post(Config.apiDomain + '/Member/showMyWinGoodsStatusMsg?token='+this.token,{data:{gid:id}});

        return res;

    }

    async getDefaultAddress(){

        let res = await Request.post(Config.apiDomain + '/Member/getUserDefaultAddress?token='+this.token);

        return res;

    }
    

    async addAddress(address){
        let res = await Request.post(Config.apiDomain + '/grouporder/addAddress',{data:address});

        return res;

    }

    async updateAddress(address){

        let res = await Request.post(Config.apiDomain + '/grouporder/setDefault',{data:address});

        return res;

    }
    
    async getAddress(){
        
        let res = await Request.post(Config.apiDomain + '/Member/getUserAddressList?token='+this.token);
        
        return res;
        
    }

    async addGoodsSendAddr(gid,addrId){

        let res = await Request.post(Config.apiDomain + '/Member/addGoodsSendAddr?token='+this.token,{data:{gid:gid,addressId:addrId}});

        return res;

    }


    async updateGoodsSendAddr(gid,addrId){

        let res = await Request.post(Config.apiDomain + '/Member/updateGoodsSendAddr?token='+this.token,{data:{gid:gid,addressId:addrId}})

        return res;

    }
    
    async confirmGetGoods(gid){
        
        let res = await Request.post(Config.apiDomain + '/Member/confirmGetGoods?token='+this.token,{data:{gid:gid}})
        
        return res
        
    }
    
    async delAddress(id){
        
        let res = await Request.post(Config.apiDomain + '/Member/delUserAddress?token='+this.token,{data:{addressId:id}});
        
        return res;
        
    }
    
    async getUserCoupon(type){
        
        let res = await Request.post(Config.apiDomain + '/Coupon/showMyCoupon',{data:{type:type,token:this.token}});
        
        return res;
        
    }
    
    async receiveUsedCoupon(aid){
        
        let res = await Request.post(Config.apiDomain + '/Coupon/receiveCoupon',{data:{aid:aid,token:this.token}});
        
        return res;
        
    }
    
    async hideMyCoupon(cid){
        
        let res = await Request.post(Config.apiDomain + '/Coupon/hideMyCoupon',{data:{cid:cid,token:this.token}});

        return res;

    }
    
    
}




let user=new User();
export default user;